<?php

namespace app\common\func;

use EasyWeChat\Factory;

class WxPay
{
    private $pay;

    public function __construct($url)
    {
        $payConfig = [
            // 必要配置
            'app_id' => Constant::$appId,
            'mch_id' => '1662661822',
            'key' => Constant::$key,   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'  => ROOT_PATH."public/file/pem/apiclient_cert.pem", // XXX: 绝对路径！！！！
            'key_path'   => ROOT_PATH."public/file/pem/apiclient_key.pem",  // XXX: 绝对路径！！！！

            'notify_url' => $url,     // 你也可以在下单时单独设置来想覆盖它
        ];

        $this->pay = Factory::payment($payConfig);
    }

    public function refundOrder($wxNo,$refundNo,$money){
        return $this->pay->refund->byTransactionId($wxNo, $refundNo, $money * 100, $money * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '用户取消',
            'notify_url' => Config("app_url")."/api/order/notifyRefund",
        ]);
    }

    public function pushOrder($body,$openid,$orderNum,$money)
    {
        $result = $this->pay->order->unify([
            'body' => $body,
            'out_trade_no' => $orderNum,
            'total_fee' => $money * 100,
//            'notify_url' => 'http://partner5.nmgfdkj.com/api/order/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);

        if($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS"){
            $jssdk = $this->pay->jssdk;

            return $jssdk->bridgeConfig($result['prepay_id'], false);
        }else{
            return $result;
        }
    }

    // 获取用户微信OPENID
    public function getWxOpenId($code)
    {
        $openid_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->secret . '&code=' . $code . '&grant_type=authorization_code';
        $res = json_decode(file_get_contents($openid_url), true);
        if (isset($res['openid'])) {
            return $res['openid'];
        } else {
            return '';
        }
    }
}
